import matplotlib.pyplot as plt
import matplotlib
import pymysql
import random
matplotlib.rcParams['font.sans-serif'] = ['SimHei']
matplotlib.rcParams['axes.unicode_minus'] = False

str_sql ="select clintion,trump,johnson from tab "




states = {"U.S."}
list=[]
def get_state():  # 将所有的州写入全局变量中
    for line in open("all_cities.txt", "r"):  # 设置文件对象并读取每一行文件
        line = line[:-1]  # 去除换行符
        states.add(line.split("'")[1])  # 将每一行文件加入到state中,只有州的名称

def chose_state():
    print("输入你需要选择的州:")
    for state in states:
        print(state)


def main():
    get_state()
    chose_state()
    state = str(input("输入你选择的州:"))
    if state in states :#存在输入的州名
        str_sql="select clinton,trump,johnson from tab"
        db =pymysql.connect(host="127.0.0.1", port=3306, user="root", passwd="4399", db="py_us_pre_ele", charset="utf8")
        cur=db.cursor()
        cur.execute(str_sql)
        for i in range(cur.rowcount-1):
            row=cur.fetchone()
            if  not 'a'in row[0]:
                clinton = float(row[0].strip())
                trump = float(row[1].strip())
                johnson = float(row[2].strip())
                tup=(clinton,trump,johnson)
                list.append(tup)
            else :
                print(row[0].strip())
        print(list)
    for tup in list:
         paint(tup,state)

def paint(tup,state):#画图
    label_list = ["川普", "希拉里", "强生", "弃权票"]  # 各部分标签
    size = [tup[0], tup[1], tup[2], 100-tup[0]-tup[1]-tup[2]]  # 各部分大小
    color = ["red", "green", "blue", "yellow"]  # 各部分颜色
    explode = [0.05, 0, 0, 0]  # 各部分突出值

    patches, l_text, p_text = plt.pie(size, explode=explode, colors=color, labels=label_list, labeldistance=1.1,
                                      autopct="%1.1f%%", shadow=False, startangle=90, pctdistance=0.6)
    plt.axis("equal")  # 设置横轴和纵轴大小相等，这样饼才是圆的
    plt.legend()
    ran_num = random.sample(range(10000), 1)
    plt.savefig("D:\\Python的数据处理图片\\"+state+str(ran_num[0])+".png")

    plt.show()






if __name__ == '__main__':
    main()

